package logic

import (
	"context"
	"fmt"
	"vipshop/cache"
	"vipshop/models"
	"vipshop/pkg"

	"vipshop/vipshoprpc/internal/svc"
	"vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *vipshoprpc.LoginRequest) (*vipshoprpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User
	models.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该账号不存在,登录失败")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误,登录失败")
	}

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if result != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误,登录失败")
	}

	s, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if s != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误,登录失败")
	}

	return &vipshoprpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
